<template>
  <div class="cart">
    <header>
      <span style="color: red" @click="isEit = !isEit">{{
        isEit ? "编辑" : "完成"
      }}</span>
      <section>购物车</section>
      <span></span>
    </header>
    <ul>
      <li v-for="(item, index) in cartList" :key="index" class="cart-list">
        <van-checkbox
          v-model="item.isCheck"
          @change="check"
          checked-color="#ee0a24"
        ></van-checkbox>
        <van-card :thumb="item.imgUrl">
          <template #tags>
            <p>{{ item.name }}</p>
            <span class="tice_center">{{ item.ties }}</span>
            <section>
              <span style="color: red">￥{{ item.price }}</span>
              <van-stepper v-model="item.buyNum" />
            </section>
          </template>
        </van-card>
      </li>
    </ul>
    <van-submit-bar
      :price="allPrice"
      :button-text="isEit ? '提交订单' : '删除选中'"
      @submit="onSubmit"
    >
      <van-checkbox
        v-model="allChecked"
        @click="$store.commit('checkAll', allChecked)"
        >全选</van-checkbox
      >
    </van-submit-bar>
  </div>
</template>

<script>
import { ref, reactive, toRefs, computed } from "vue";
import { useStore } from "vuex";
export default {
  setup() {
    const store = useStore();
    const data = reactive({
      isEit: true, // 编辑
      cartList: computed(() => store.state.cartList),
      allChecked: false,
      allPrice: computed(() => {
        let price = 0;
        data.cartList.forEach((item) => {
          if (item.isCheck) {
            price += item.price * item.buyNum;
          }
        });
        return price * 100;
      }),
    });
    const onSubmit = () => {
      if (data.isEit) return;
      store.commit("delect");
    };
    const check = () => {
      // 反选
      data.allChecked = data.cartList.every((item) => item.isCheck);
    };
    return {
      ...toRefs(data),
      onSubmit,
      check,
    };
  },
};
</script>
<style lang="scss" scoped>
.cart {
  header {
    display: flex;
    height: 50px;
    align-items: center;
    border-bottom: 1px solid #ccc;
    span {
      width: 60px;
      text-align: center;
    }
    section {
      flex: 1;
      text-align: center;
    }
  }
}
.cart-list {
  display: flex;
  align-items: center;
  padding: 0 10px;
  .van-card {
    flex: 1;
    background: #fff;
    p {
      line-height: 40px;
    }
    .tice_center {
      color: #ccc;
    }
    section {
      margin-top: 5px;
      display: flex;
      justify-content: space-between;
    }
  }
}
.van-submit-bar {
  bottom: 50px;
}
</style>